package com.cybertron.ironhide.manage.util;

import org.htmlparser.Node;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.PrototypicalNodeFactory;
import org.htmlparser.nodes.TextNode;
import org.htmlparser.tags.ImageTag;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;

import com.cybertron.ironhide.manage.common.Constants;
import com.cybertron.ironhide.manage.common.html.BrTagNode;

public class ContentUtil {

	public static String visitModifier(String content) {
		if (content == null) {
			return null;
		}
		StringBuffer result = new StringBuffer();
		Parser parser = new Parser();
		PrototypicalNodeFactory nodeFactory = new PrototypicalNodeFactory();
		nodeFactory.registerTag(new BrTagNode());
		parser.setNodeFactory(nodeFactory);
		try {
			parser.setInputHTML(content);
			NodeList nodeList = parser
					.extractAllNodesThatMatch(new NodeFilter() {
						private static final long serialVersionUID = 1L;

						@Override
						public boolean accept(Node node) {
							return true;
						}
					});
			for (int i = 0; i < nodeList.size(); i++) {
				Node node = nodeList.elementAt(i);
				if (node instanceof ImageTag) {
					ImageTag imageTag = (ImageTag) node;
					String imageUrl = imageTag.getImageURL();
					if (imageUrl.startsWith("http")) {
						imageTag.setImageURL(imageUrl);
					} else {
						imageTag.setImageURL(Constants.RESOURCE_ROOT_URL
								+ imageUrl);
					}
					result.append(imageTag.toHtml());
				} else if (node instanceof TextNode) {
					TextNode text = (TextNode) node;
					result.append(text.getText());
				} else {
					result.append('<');
					result.append(node.getText());
					result.append('>');
				}
			}
		} catch (ParserException e) {
			e.printStackTrace();
		}
		return result.toString();
	}
}
